package com.superhelper.app.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.superhelper.app.domain.Resp;
import com.superhelper.common.Consts;
import com.superhelper.common.exception.ServiceException;
import com.superhelper.common.utils.JsonHelper;


public class MyExceptionHandler implements HandlerExceptionResolver {
    protected Logger log = LoggerFactory.getLogger(MyExceptionHandler.class);

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        log.error("{} error,agent:{},version:{},device:{},model:{}", request.getRequestURI(),
                request.getHeader("user-agent"), request.getHeader("gzVersion"), request.getHeader("device"),
                request.getHeader("model"), ex);
        ModelAndView view = new ModelAndView("error");
        request.setAttribute("errorMsg", JsonHelper.toJson(error(ex)));

        return view;
    }

    protected Resp error(Throwable t) {
    	ServiceException ge = null;
        if (t instanceof ServiceException) {
            ge = (ServiceException) t;
        } else {
            ge = new ServiceException();
			ge.setCode(Consts.Code.INTERNAL_ERROR);
            ge.setMsg("error");
        }
        Resp resp = new Resp(ge.getCode(), ge.getMsg());
        return resp;
    }
}